package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

    @Value("${image.url}")
    private String imageUrl;

    @PostMapping("/fileUpload")
    public Result fileUpload(@RequestParam MultipartFile file) {
        StorageClient1 storageClient1 = null;
        try {
            String path = ClassUtils.getDefaultClassLoader().getResource(
                    "tracker-server.conf").getFile();
            ClientGlobal.init(path);

            TrackerClient trackerClient = new TrackerClient();

            TrackerServer trackerServer = trackerClient.getConnection();

            storageClient1 = new StorageClient1(trackerServer, null);

            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            String fileId = storageClient1.upload_file1(file.getBytes(), ext, null);
            System.out.println("fileId = " + (imageUrl + fileId));

            return Result.ok(imageUrl + fileId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail();
    }

}
